﻿using System;
using System.Collections.Generic;
using System.Threading;
using System.Windows.Forms;
using AMM.Business.Produce;
using AMM.CustomWinControls;
using AMM.Model;
using AMM.Model.Produce;
using AMM.UserControls;

namespace AMM.Forms.Produce {
    public partial class FrmProducePlan : FrmProducePlanBase {

        private int _pageIndex;
        private ProducePlanSearchModel _searchModel;
        private ProducePlanProcessor _producePlanProcessor;
        private List<ProduceConductForPlanViewModel> _produceConductList;

        #region Override

        protected override string FunctionCode {
            get { return "AMM1502"; }
        }

        protected override BaseSearchControl SearchControl {
            get { return new ProduceConductSearchControl(); }
        }

        protected override void Add() {
            this.ResetForms();
            this.ShowEditForm("新增", new List<ProducePlan>());
            base.Add();
        }

        protected override void Amend() {
            List<ProduceConductForPlanViewModel> selectedList = this.dgvProduceConductList.GetSelectedRows<ProduceConductForPlanViewModel>();
            if (selectedList.Count > 1) { this.OnlySelectSingleRecord(); return; }
            if (selectedList.Count == 0) { this.ShouldSelectSingleRecord(); return; }
            List<ProducePlan> producePlanList = this._producePlanProcessor.FetchProducePlanByProduceConductId(selectedList[0].Key);
            this.ShowEditForm("修改", producePlanList);
            base.Amend();
        }

        protected override void Save() {
            base.Save();
        }

        protected override void Search(object sender, FrmSearch.SearchArgs e) {
            this.CreateNewThread(() => {
                if (e.IsRevert) {
                    this._searchModel = new ProducePlanSearchModel();
                }
                else {
                    this._searchModel = (ProducePlanSearchModel)e.SearchModel;
                }
            }, () => {
                this.BindProduceConductList();
            });
        }

        #endregion

        public FrmProducePlan() {
            this.InitializeComponent();

            this.dgvProduceConductList.DataGridViewModelType = typeof(ProduceConductForPlanViewModel);
            this.dgvproducePlanList.DataGridViewModelType = typeof(ProducePlanViewModel);
        }

        #region Private methods

        private bool frmEdit_Edit(object sender, FrmEdit.EditArgs e) {
            bool resultFlag = false;
            List<ProducePlan> producePlanList = (List<ProducePlan>)e.EditModel;
            //if (producePlanList.Count == 0) {
            //    this.ShowError("请添加生产计划明细记录！");
            //    return false;
            //}
            this.PreventCancel = true;
            this.CreateNewThread(() => {
                producePlanList.ForEach(x => {
                    if (x.ClassStatus == ClassStatus.Added) {
                        x.CreatedBy = LoginUserName;
                    }
                    else {
                        x.ModifiedBy = LoginUserName;
                    }
                });
                this._producePlanProcessor.Update(producePlanList);

                resultFlag = true;
            }, () => {
                this.ResetForms();
                this.PreventCancel = false;
                if (resultFlag) {
                    this.MDIParent.SetStatusInformation("保存成功");
                    this.FormEdit.Close();
                }
            });

            this.Save();
            return true;
        }

        private void ResetForms() {
            this.BindProduceConductList();
            this.BindproducePlanList(0);
        }

        private void BindProduceConductList() {
            this.CreateNewThread(() => {
                this._produceConductList = this._producePlanProcessor.FetchProduceConductForPlanViewModelList(this._searchModel, this._pageIndex);
            }, () => {
                this.dgvProduceConductList.DataSource = new SortableBindingList<ProduceConductForPlanViewModel>(this._produceConductList);
                this.pceList.Records = this._searchModel.Records;
                this.pceList.DataBind();
            });
        }

        private void BindproducePlanList(int produceConductId) {
            List<ProducePlanViewModel> detailsList = new List<ProducePlanViewModel>();
            this.CreateNewThread(() => {
                if (produceConductId != 0) {
                    detailsList = this._producePlanProcessor.FetchProducePlanViewModelByProduceConductIdList(produceConductId);
                }
            }, () => {
                this.dgvproducePlanList.DataSource = new SortableBindingList<ProducePlanViewModel>(detailsList);
            });
        }

        private void ShowEditForm(string title, List<ProducePlan> producePlanList) {
            this.CreateNewThread(() => {
                Thread.Sleep(100);
            }, () => {
                ProducePlanEditControl editControl = new ProducePlanEditControl();
                this.FormEdit = new FrmEdit();
                editControl.BaseEditModel = producePlanList;
                editControl.ValidatorForEdit = this.FormEdit.validatorForEdit;
                this.FormEdit.Controls.Add(editControl);
                this.FormEdit.Edit += new FrmEdit.EditEventHandler(frmEdit_Edit);
                this.FormEdit.Text = string.Format("{0}{1}", title, this.Text);
                FrmEntry.LoadAndRunDialog(this.FormEdit);
            });
        }

        #endregion

        private void FrmProducePlan_Load(object sender, EventArgs e) {
            this.CreateNewThread(() => {
                this.PreventCancel = true;
                this._producePlanProcessor = new ProducePlanProcessor(this.pceList.PageSize);
                this._searchModel = new ProducePlanSearchModel();
                this._pageIndex = 1;
            }, () => {
                this.WindowState = FormWindowState.Maximized;
                this.ResetForms();
                this.PreventCancel = false;
            });
        }

        private void pceList_Paging(object sender, PaginationArgs e) {
            this._pageIndex = e.PageIndex;
            this.BindProduceConductList();
        }

        private void dgvProduceConductList_DoubleClick(object sender, EventArgs e) {
            if (this.dgvProduceConductList.CurrentRow != null) {
                int produceConductId = (int)this.dgvProduceConductList.CurrentRow.Cells["Key"].Value;
                this.BindproducePlanList(produceConductId);
            }
        }
    }
}
